package org.jash.user.register

import com.example.common.mvi.BaseRepository
import com.example.common.mvi.NetworkConfig
import com.example.common.mvi.NetworkResult
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RegisterRepository : BaseRepository() {
    private val api: RegisterApi by lazy {
        Retrofit.Builder()
            .baseUrl("http://10.161.9.80:7015/")
            .client(NetworkConfig.createOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create(NetworkConfig.createGson()))
            .build()
            .create(RegisterApi::class.java)
    }

    fun register(username: String, password: String): Flow<NetworkResult<RegisterEntity>> {
        return safeApiCall { api.register(username, password) }.map { result ->
            when (result) {
                is NetworkResult.Success -> {
                    val entity = result.data
                    if (entity.code == 200) {
                        NetworkResult.Success(entity)
                    } else {
                        NetworkResult.Error(Exception(entity.msg))
                    }
                }
                is NetworkResult.Error -> result
                is NetworkResult.Loading -> result
            }
        }
    }
}
